<!-- Vue组件 -->
<template>
  <div class="cesiumContainerBox">
    <div id="cesiumContainer" style="width: 100%; height: 91vh"></div>
  </div>
</template>

<script>
export default {
  name: "CesiumConViewer",
  props: {
    cesiumData: {
      type: Object,
      default: () => ({ reals: {}, tracks: {} }),
    },
  },
  data() {
    return {
      viewer: null,
      entities: [],
    };
  },
  watch: {
    cesiumData: {
      deep: true,
      handler(newData) {
        // 检查空数据
        if (
          !newData ||
          (//Object.keys(newData.reals).length === 0 &&
            Object.keys(newData.tracks).length === 0)
        ) {
          console.warn("CesiumConViewer: 接收到空数据，跳过渲染");
          return;
        }

        this.clearTracks();
        this.drawTracks(newData);
      },
    },
  },
  mounted() {
    this.initCesiumContainer();
  },
  methods: {
    //初始化cesium
    initCesiumContainer() {
      this.viewer = new Cesium.Viewer("cesiumContainer", {
        baseLayerPicker: false,
        imageryProvider: false,
        sceneMode: Cesium.SceneMode.SCENE2D,
        animation: false,
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        timeline: false,
        infoBox: false,
        fullscreenButton: true,
      });
      // 获取默认的必应底图并移除（如果存在）
      const defaultLayer = this.viewer.imageryLayers.get(0);
      if (defaultLayer) {
        this.viewer.imageryLayers.remove(defaultLayer);
      }

      //瓦片图中心显示
      var centerLongitude = 131;
      var centerLatitude = 40.81;
      var halfSize = 0.05;

      // 创建限定显示范围的矩形区域
      var rectangle = Cesium.Rectangle.fromDegrees(
        centerLongitude - halfSize,
        centerLatitude - halfSize,
        centerLongitude + halfSize,
        centerLatitude + halfSize
      );

      // 禁用用户平移操作
      this.viewer.scene.screenSpaceCameraController.enableTranslate = true;
      // 设置初始视图到矩形中心
      var initialPosition = Cesium.Rectangle.center(rectangle);
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromRadians(
          initialPosition.longitude,
          initialPosition.latitude,
          500000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: 0,
        },
      });
      // 可选：进一步限制交互
      this.viewer.scene.screenSpaceCameraController.enableRotate = false;
      this.viewer.scene.screenSpaceCameraController.enableTilt = false;

      // 加载本地瓦片（需提前配置离线数据源）
      const offlineProvider = new Cesium.UrlTemplateImageryProvider({
        url: "/gismap/{z}/{y}/{x}.png",
        minimumLevel: 0,
        maximumLevel: 8,
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
      });
      this.viewer.imageryLayers.addImageryProvider(offlineProvider);

      this.viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10000;
      this.viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000000;
    },
    drawTracks(data) {
      // 绘制真值航迹（红色）
      // Object.values(data.reals).forEach((track) => {
      //   this.drawTrack(track, Cesium.Color.RED.withAlpha(0.4));
      // });

      // 绘制雷达航迹（绿色）
      Object.values(data.tracks).forEach((track) => {
        this.drawTrack(track, Cesium.Color.GREEN.withAlpha(0.7));
      });
    },
    drawTrack(points, color) {
      if (!points || points.length < 2) {
        console.warn("CesiumConViewer: 航迹点不足2个，跳过绘制");
        return;
      }

      // 过滤无效点（只需要经纬度）
      const validPoints = points.filter(
        (p) => !isNaN(p.longitude) && !isNaN(p.latitude)
      );

      if (validPoints.length < 2) {
        console.error("CesiumConViewer: 有效航迹点不足2个，无法绘制");
        return;
      }

      // 创建航迹线（忽略高度）
      try {
        const positions = validPoints.flatMap((p) => [p.longitude, p.latitude]);
        const polyline = this.viewer.entities.add({
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(positions),
            width: 3,
            material: color,
            clampToGround: false, // 不贴地
          },
        });
        this.entities.push(polyline);
      } catch (error) {
        console.error("CesiumConViewer: 创建航迹线失败", error);
      }
      // 在第一个点添加飞机实体
      const startPoint = validPoints[0];
      this.addPlaneEntity(startPoint, color);
    },
    addPlaneEntity(point, color) {
      try {
        // 创建飞机实体
        const plane = this.viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            point.longitude,
            point.latitude
          ),
          billboard: {
            image: require("@/assets/images/airplane.svg"),
            width: 15,
            height: 15,
            zIndex: 20, // 设置最高的 zIndex
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
          // 在飞机头部添加批号标签
          label: {
            text: String(point.batchNo),
            font: "14px sans-serif",
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(0, -25), // 在飞机下方显示
          },
        });

        this.entities.push(plane);
        return plane;
      } catch (error) {
        console.error("CesiumConViewer: 创建飞机实体失败", error);
        return null;
      }
    },
    clearTracks() {
      this.entities.forEach((entity) => this.viewer.entities.remove(entity));
      this.entities = [];
    },
  },
  beforeDestroy() {
    if (this.viewer) {
      this.viewer.destroy();
    }
  },
};
</script>

<style lang="less" scoped>
/* 移除冗余样式 */
.cesiumContainerBox {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 全局样式 */
::v-deep .cesium-credit-textContainer,
::v-deep .cesium-credit-logoContainer,
::v-deep .cesium-credit-expand-link {
  display: none !important;
}
</style>
